<script>
import ProjectSelector from "@/components/Selector/ProjectSelector.vue";
import ExpenseLedgerSelector from "@/components/Selector/ExpenseLedgerSelector.vue";
import { defineComponent } from "vue";
import { http } from "@/utils/http/index.ts";
import {
  list,
  uploadChronological,
  mappingTypes,
  standard
} from "@/api/projectChronologicalLedger";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "import-auxiliary-ledger",
  components: { ProjectSelector, ExpenseLedgerSelector },
  data() {
    return {
      uploadDisplay: false,
      tableData: [],
      selected: [],
      query: {
        projectId: "",
        // 当前页码
        currPage: 1,
        // 页尺寸
        pageSize: 10,
        // 页总记录数
        // 刷新按钮
        lst: false
      },
      pageTotal: 0,
      someStandardDisplay: false,
      standMapping: {},
      allStandardDisplay: false,
      allMapping: [],
      color: [
        "var(--el-color-primary)",
        "var(--el-color-warning)",
        "var(--el-color-success)"
      ]
    };
  },
  computed: {
    selectedMapping() {
      let set = new Set();
      this.selected.forEach(s => set.add(s.thirdSubject));
      return set;
    }
  },
  watch: {
    query: {
      handler() {
        this.getList();
      },
      immediate: true,
      deep: true
    }
  },
  async mounted() {},
  methods: {
    checkProject() {
      if (!this.query.projectId) {
        ElMessage({
          message: "请先选择项目",
          type: "error"
        });
        return true;
      }
      return false;
    },
    async standardItem(isAll) {
      if (!isAll) {
        if (!this.selected?.length) {
          ElMessage({
            message: "请先选择序时账",
            type: "error"
          });
        }
        await standard({
          batchIds: this.selected.map(i => i.id),
          projectId: this.query.projectId,
          mapping: this.standMapping
        });
        this.someStandardDisplay = false;
      } else {
        await standard({
          projectId: this.query.projectId,
          mapping: this.standMapping
        });
        this.allStandardDisplay = false;
      }

      await this.getList();
    },
    downloadXushizhang() {
      http.download("/project/chronological/template");
    },
    async getList() {
      if (!this.query.projectId) {
        this.tableData = [];
      }
      let res = await list({
        current: this.query.currPage,
        size: this.query.pageSize,
        projectId: this.query.projectId
      });
      this.tableData = res.data.records;
      this.pageTotal = res.data.total;
    },
    // 数据页码长度变化
    pageSizeChange(pageSize) {
      this.query.pageSize = pageSize;
      this.query.currPage = 1;
      this.getList();
    },
    // 数据页码变化
    currPageChange(pageIndex) {
      this.query.currPage = pageIndex;
      this.getList();
    },
    async handleFileUpload(file) {
      await uploadChronological(this.query.projectId, file.file);
      this.uploadDisplay = false;
      ElMessage({
        message: "导入成功",
        type: "success"
      });
      await this.getList();
    },
    uploadFile() {
      this.$refs.fileImportCom.submit();
    },
    handleSelectionChange(rows) {
      console.log({ rows });
      this.selected = rows;
    },
    openSomeStandard() {
      if (this.selected.length === 0) {
        ElMessage({
          message: "请先选择序时账帐",
          type: "error"
        });
      } else {
        this.standMapping = {};
        this.someStandardDisplay = true;
      }
    },
    async openAllStandard() {
      if (!this.query.projectId) {
        ElMessage({
          message: "请先选择项目",
          type: "error"
        });
        return;
      }
      this.standMapping = {};
      this.allStandardDisplay = true;
      let res = await mappingTypes(this.query.projectId);
      if (res.code === 200) {
        this.allMapping = res.data;
      }
    },
    openUpload() {
      if (!this.query.projectId) {
        ElMessage({
          message: "请先选择项目",
          type: "error"
        });
      } else {
        this.uploadDisplay = true;
      }
    }
  }
});
</script>

<template>
  <div>
    <header>
      <ProjectSelector v-model="query.projectId" />
      &nbsp;
      <el-button type="primary" @click="openUpload"> 导入序时账</el-button>
      <el-button type="primary" @click="openSomeStandard">
        批量序时账标准化
      </el-button>
      <el-button type="primary" @click="openAllStandard">
        全部序时账标准化
      </el-button>
    </header>

    <!--数据-->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="voucher" label="凭证号" />
      <el-table-column prop="abstractContent" label="摘要" />
      <el-table-column prop="startTime" label="开始时间" />
      <el-table-column prop="firstSubject" label="第一科目" />
      <el-table-column prop="secondSubject" label="第二科目" />
      <el-table-column prop="thirdSubject" label="第三科目" />
      <el-table-column prop="flow" label="流向" />
      <el-table-column prop="amount" label="金额" />
      <el-table-column prop="standSubject" label="标准科目">
        <template #default="scope">
          {{ scope.row.standSubject ?? "未标准化" }}
        </template>
      </el-table-column>
    </el-table>
    <!-- 常规数据分页开始 -->
    <el-pagination
      v-model::current-page="query.currPage"
      v-model:page-size="query.pageSize"
      :total="pageTotal"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      layout="prev,pager,next,jumper,sizes,total"
      @size-change="pageSizeChange"
      @current-change="currPageChange"
    />
    <el-dialog v-model="uploadDisplay" title="导入序时账" width="500">
      <el-upload
        ref="fileImportCom"
        class="upload-demo"
        drag
        :limit="1"
        :auto-upload="false"
        :http-request="handleFileUpload"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖动到此处或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            没有序时账模板？<a style="color: blue" @click="downloadXushizhang"
              >点击下载</a
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="uploadFile"> 导入</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="someStandardDisplay"
      title="批量序时账标准化"
      width="500"
      destroy-on-close
    >
      <el-form label-width="auto" style="max-width: 600px">
        <el-form-item v-for="item in selectedMapping" :key="item" :label="item">
          <ExpenseLedgerSelector v-model="standMapping[item]" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="standardItem(false)">
            立即标准化</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="allStandardDisplay"
      title="全部序时账标准化"
      width="500"
      destroy-on-close
    >
      <el-tag type="primary">从未标准化</el-tag>&nbsp;
      <el-tag type="success">已标准化</el-tag>&nbsp;
      <el-tag type="warning">部分标准化</el-tag>&nbsp;
      <div>如果不选，则该项不标准化，选择后该项会全部标准化为目标项</div>
      <el-form label-width="auto" style="max-width: 600px">
        <el-form-item v-for="item in allMapping" :key="item.thirdSubject">
          <slot name="label">
            <el-popover
              v-if="item.standSubjects.length"
              placement="top-start"
              title="已标准化项"
              :width="200"
              trigger="hover"
              :content="item.standSubjects.join(',')"
            >
              <template #reference>
                <span :style="{ color: color[item.state] }"
                  >{{ item.thirdSubject }}&nbsp;&nbsp;&nbsp;</span
                >
              </template>
            </el-popover>
            <template v-else>
              <span :style="{ color: color[item.state] }"
                >{{ item.thirdSubject }} &nbsp;&nbsp;&nbsp;</span
              >
            </template>
          </slot>
          <ExpenseLedgerSelector v-model="standMapping[item.thirdSubject]" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="standardItem(true)">
            立即标准化</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
.layout-card {
  margin-top: 20px;
}
</style>
